package com.fattyCorps.controller;


import com.fattyCorps.config.gameConfig.GlobalMailConfig;
import com.fattyCorps.obj.cache.player.packet.Mail;
import com.fattyCorps.obj.msg.SRet;
import com.fattyCorps.obj.msg.client.mail.CAddGlobalMailMsg;
import com.fattyCorps.obj.msg.client.mail.CAddMailMsg;
import com.fattyCorps.obj.msg.client.mail.CGetAttachmentMsg;
import com.fattyCorps.obj.msg.client.mail.CReadMailMsg;
import com.fattyCorps.obj.msg.server.mail.*;
import com.fattyCorps.service.MailService;
import com.fattyCorps.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    MailService mailService;

    @Autowired
    GlobalMailConfig globalMailConfig;

    @PostMapping("/getMailList")
    public SRet getMailList(HttpServletRequest request){
        Integer playerId = ServletUtils.getPlayerIdByRequest(request);

        List<Mail> mailList = mailService.getMailList(playerId);
        SGetMailListMsg msg = new SGetMailListMsg();
        msg.setMails(mailList);

        return SRet.success(msg);
    }

    @PostMapping("/addMail")
    public SRet addMail(HttpServletRequest request, @RequestBody CAddMailMsg cAddMailMsg) {
        mailService.addMail(cAddMailMsg.getPlayerId(), cAddMailMsg.getTitle(), cAddMailMsg.getContent(), cAddMailMsg.getAttachment());
        return SRet.success();
    }

    @PostMapping("/addGlobalMail")
    public SRet addGlobalMail(HttpServletRequest request, @RequestBody CAddGlobalMailMsg cAddGlobalMailMsg) {
        globalMailConfig.addGlobalMailInDb(cAddGlobalMailMsg.getTitle(), cAddGlobalMailMsg.getContent(), cAddGlobalMailMsg.getAttachment());
        return SRet.success();
    }

    @PostMapping("/readMail")
    public SRet readMail(HttpServletRequest request, @RequestBody CReadMailMsg cReadMailMsg) {
        Integer playerId = ServletUtils.getPlayerIdByRequest(request);
        mailService.readMail(playerId, cReadMailMsg.getMailId());

        SReadMailMsg msg = new SReadMailMsg();
        msg.setMailId(cReadMailMsg.getMailId());
        return SRet.success(msg);
    }

    @PostMapping("/getAttachment")
    public SRet getAttachment(HttpServletRequest request, @RequestBody CGetAttachmentMsg cGetAttachmentMsg) {
        Integer playerId = ServletUtils.getPlayerIdByRequest(request);
        mailService.getAttachment(playerId, cGetAttachmentMsg.getMailId());

        SGetAttachmentMsg msg = new SGetAttachmentMsg();
        msg.setMailId(cGetAttachmentMsg.getMailId());
        return SRet.success(msg);
    }
}
